import pymysql


class MyORM:
    def __init__(self):
        conn = pymysql.connect(
            host='127.0.0.1',
            port=3306,
            user='root',
            password='123456',
            database='mumushouji',
            charset='utf8',
            autocommit=True,
            cursorclass=pymysql.cursors.DictCursor
        )
        cursor = conn.cursor()
        self.cursor = cursor

    def execute(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()


class Model:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            self.__setattr__(k, v)

    def fields(self, select_params=None):
        self.columns = ','.join(select_params)
        return self

    def query(self, **where_params):
        table = self.__class__.__getattribute__(self, 'table_name')
        if hasattr(self, 'columns'):
            sql = 'select %s from %s' % (self.columns, table)
        else:
            sql = 'select * from %s' % table

        if where_params is not None:
            sql += ' where '
            for k, v in where_params.items():
                sql += " %s = '%s' and" % (k, v)
            sql += ' 1=1 limit 1'

        print(sql)
        return MyORM().execute(sql)

    def insert(self):
        table = self.__class__.__getattribute__(self, 'table_name')
        keys, values = [], []
        for k, v in self.__dict__.items():
            keys.append(k)
            values.append(v)
        sql = 'insert into %s(%s) values("%s")' % (table, ','.join(keys), '","'.join(values))
        print(sql)
        return MyORM().execute(sql)


class User(Model):
    table_name = 'user'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class Article(Model):
    table_name = 'article'


if __name__ == '__main__':
    from icecream import ic

    # user = User(username='dazhoulaoshi2', password='1232', nickname='大周老师2', picture='2.jpg', job='全栈工程师2')
    # user.insert()
    # user = User()
    # print(user.fields(['username', 'nickname']).query(user_id=3))

    article = Article()
    print(article.fields(['label_name', 'title']).query(id=5))
